package com.supcon.tinyportal.tags;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class HandlerTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	private String key;

	public String getEvent() {
		return event;
	}

	public void setEvent(String event) {
		this.event = event;
	}

	private String event;

	@SuppressWarnings("unchecked")
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		if (event == null && key == null ) {
			if ("POST".equalsIgnoreCase(request.getMethod())) {
				return EVAL_BODY_INCLUDE;
			}
		} else {
			Enumeration reqParams = request.getParameterNames();
			while (reqParams.hasMoreElements()) {
				String actualKey = (String) reqParams.nextElement();
				String paramValue = null;
				if (key != null && event != null) {
					if (actualKey.equals(key) || actualKey.equals(key + ".x")) {
						paramValue = request.getParameter(actualKey);
						if (event.equals(paramValue)) {
							return EVAL_BODY_INCLUDE;
						}
					}
				} else if (event != null && (actualKey.equals(event) || actualKey.equals(event + ".x"))) {
					return EVAL_BODY_INCLUDE;
				} else if (key != null && (actualKey.equals(key) || actualKey.equals(key + ".x"))) {
					return EVAL_BODY_INCLUDE;
				}
			}
		}
		return SKIP_BODY;
	}
}
